/* $RCSFile: ModuleSettingsPage.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Modules/ModuleSettingsPage.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:57  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Settings;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using System.Globalization;

namespace AddonNice.PageModules.Modules
{
    /// <summary>
    /// Use this page to modify title and permission on portal modules<br />
    /// The ModuleSettingsPage.aspx page is used to enable administrators to view/edit/update
    /// a portal module's settings (title, output cache properties, edit access)
    /// </summary>
    public partial class ModuleSettingsPage : PropertyPage
	{
        /// <summary>
        /// The Page_Load server event handler on this page is used
        /// to populate the module settings on the page.
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage Page_Load BEG.",PageTraceSwitch.Sw.Info);
            if (!IsPostBack)
                BindData();
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage Page_Load END.",PageTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Allow update in demo mode
        /// </summary>
        protected override void OnUpdate(ADNPageEventArgs e)
        {
            e.OverrideDemo  =   true;
            base.OnUpdate(e);
		}

        /// <summary>
        /// Save the module settings into the portal configuration system.
        /// </summary>
        void ModuleSettingsPage_Update(object sender, AddonNice.UI.ADNPageEventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage ModuleSettingsPage_Update BEG.",PageTraceSwitch.Sw.Info);
            ModuleConfiguration m           =   GetModuleConfiguration();
            if ( m == null )
				return;
			try
			{
				// Edit Roles
				StringBuilder sb            =   new StringBuilder();
				foreach (ListItem editItem in authEditRoles.Items)
				{
					if (editItem.Selected)
					{
						if (editItem.Text == CRMAllUsers)
							editItem.Text   =   DBAllUser;
						else if (editItem.Text == CRMAdmin)
							editItem.Text   =   DBAdmin;
						sb.AppendFormat("{0};", editItem.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update selected Edit role: {0}", editItem.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string editRoles            =   sb.ToString(); 
                m.AuthorizedEditRoles       =   editRoles;
				// View Roles
				sb                          =   new StringBuilder();
				foreach (ListItem viewItem in authViewRoles.Items)
				{
					if (viewItem.Selected)
					{
						if (viewItem.Text == CRMAllUsers)
							viewItem.Text   =   DBAllUser;
						else if (viewItem.Text == CRMAdmin)
							viewItem.Text   =   DBAdmin;
						sb.AppendFormat("{0};", viewItem.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update select View role: {0}", viewItem.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string viewRoles            =   sb.ToString();
                m.AuthorizedViewRoles       =   viewRoles;
				
                // Add Roles
				sb                          =   new StringBuilder();
				foreach (ListItem addItem in authAddRoles.Items)
				{
					if (addItem.Selected)
					{
						if (addItem.Text == CRMAllUsers)
							addItem.Text    =   DBAllUser;
						else if (addItem.Text == CRMAdmin)
							addItem.Text    =   DBAdmin;
						sb.AppendFormat("{0};", addItem.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update select Add role: {0}", addItem.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string addRoles             =   sb.ToString(); 
                m.AuthorizedAddRoles        =   addRoles;

				// Delete Roles
				sb                          =   new StringBuilder();
				foreach (ListItem deleteItem in authDeleteRoles.Items)
				{
					if (deleteItem.Selected)
					{
						if (deleteItem.Text == CRMAllUsers)
							deleteItem.Text =   DBAllUser;
						else if (deleteItem.Text == CRMAdmin)
							deleteItem.Text =   DBAdmin;
						sb.AppendFormat("{0};", deleteItem.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage OnUpdate select Delete role: {0}", deleteItem.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string deleteRoles          =   sb.ToString();
                m.AuthorizedDeleteRoles     =   deleteRoles;

				// Move Module Roles
				sb                          =   new StringBuilder();
				foreach (ListItem li in authMoveModuleRoles.Items)
				{
					if (li.Selected)
					{
						if (li.Text == CRMAllUsers)
							li.Text         =   DBAllUser;
						else if (li.Text == CRMAdmin)
							li.Text         =   DBAdmin;
						sb.AppendFormat("{0};", li.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update select Move role: {0}", li.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string moveModuleRoles      =   sb.ToString();
				m.AuthorizedMoveModuleRoles =   moveModuleRoles; 
                
                // Delete Module Roles
				sb                          =   new StringBuilder();
				foreach (ListItem li in authDeleteModuleRoles.Items)
				{
					if (li.Selected)
					{
						if (li.Text == CRMAllUsers)
							li.Text         =   DBAllUser;
						else if (li.Text == CRMAdmin)
							li.Text         =   DBAdmin;
						sb.AppendFormat("{0};", li.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update select DeleteModule role: {0}", li.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string deleteModuleRoles        =   sb.ToString();
                m.AuthorizedDeleteModuleRoles   =   deleteModuleRoles;

				// Properties Roles
				sb                              =   new StringBuilder();
				foreach (ListItem PropertiesItem in authPropertiesRoles.Items)
				{
					if (PropertiesItem.Selected)
					{
						if (PropertiesItem.Text == CRMAllUsers)
							PropertiesItem.Text = DBAllUser;
						else if (PropertiesItem.Text == CRMAdmin)
							PropertiesItem.Text = DBAdmin;
						sb.AppendFormat("{0};", PropertiesItem.Text);
						if (PageTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update select Properties role: {0}", PropertiesItem.Text),PageTraceSwitch.Sw.Info);
					}
				}
				string PropertiesRoles          =   sb.ToString();
                m.AuthorizedPropertiesRoles     =   PropertiesRoles;

				if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage ModuleSettingsPage_Update before update module in DB tabDropDownList.SelectedValue: {0}, tabDropDownList.SelectedItem.Value: {1}", 
                        tabDropDownList.SelectedValue,tabDropDownList.SelectedItem.Value),PageTraceSwitch.Sw.Info);
                m.ModuleSettingsID              =   Int32.Parse(ComboModules.SelectedValue);
				// update module
				new ModulesDB().UpdateModule(Int32.Parse(tabDropDownList.SelectedValue), 
                    ModuleID, 
                    m.ModuleOrder, 
                    m.ModuleSettingsID,
                    m.PaneName, 
                    moduleTitle.Text, 
                    Int32.Parse(cacheTime.Text), 
                    editRoles, viewRoles, addRoles, deleteRoles, PropertiesRoles, moveModuleRoles, deleteModuleRoles, 
                    showEveryWhere.Checked, 
                    allowCollapsable.Checked);

				// Update Textbox Settings
				m.ModuleTitle                   = moduleTitle.Text;


				// Populate checkbox list with all security roles for this portal
				// and "check" the ones already configured for this module
				populateRoles(authEditRoles, m.AuthorizedEditRoles);
				populateRoles(authViewRoles, m.AuthorizedViewRoles);
				populateRoles(authAddRoles, m.AuthorizedAddRoles);

				populateRoles(authDeleteRoles, m.AuthorizedDeleteRoles);
				populateRoles(authPropertiesRoles, m.AuthorizedPropertiesRoles);

				populateRoles(authMoveModuleRoles, m.AuthorizedMoveModuleRoles);
				populateRoles(authDeleteModuleRoles, m.AuthorizedDeleteModuleRoles);
			}
			catch (Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleSettingsPage ModuleSettingsPage_Update moduleID : {0}, ex : {1}", ModuleID, ex),PageTraceSwitch.Sw.Info);
                throw;
			}
        }


        /// <summary>
        /// Used to populate all checklist roles with Roles in portal
        /// </summary>
        private void populateRoles(CheckBoxList listRoles, string moduleRoles)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage populateRoles listRoles: {0}, moduleRoles: {1}",listRoles.ID, moduleRoles),PageTraceSwitch.Sw.Info);
            string CRMAdmin         =   Config.CRMAdminRole;
            string DBAdmin          =   Config.InternalAdminRole;

            // Clear existing items in checkboxlist
            listRoles.Items.Clear();

            ListItem allItem        =   new ListItem(CRMAllUsers);
            listRoles.Items.Add(allItem);

            // get the CRM Roles
            string[] CrmRoles       =   PortalSecurity.GetCRMRoles();
            foreach (string cr in CrmRoles)
            {
                ListItem lItem      =   new ListItem(cr);
                listRoles.Items.Add(lItem);
            }


            //Splits up the role string and use array 
			moduleRoles.TrimEnd();
            string[] arrModuleRoles =   moduleRoles.Split(new char[] { ';' },StringSplitOptions.RemoveEmptyEntries);
            int roleCount           =   arrModuleRoles.GetUpperBound(0);

            // We transform the internal Admin in CRM admin to check ok later
            for (int i = 0; i <= roleCount; i++)
            {
                if (arrModuleRoles[i] == DBAdmin)
                    arrModuleRoles[i] = CRMAdmin;
				else if (arrModuleRoles[i] == DBAllUser )
					arrModuleRoles[i] = CRMAllUsers;
            }
            //Cycle every role and select it if needed
            foreach (ListItem ls in listRoles.Items)
            {
                for (int i = 0; i <= roleCount; i++)
                {
                    if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage populateRoles arrModuleRoles[{0}]: {1}, ls: {2}",i,arrModuleRoles[i],ls.Text),PageTraceSwitch.Sw.Info);
                    if (arrModuleRoles[i].ToLower(CultureInfo.InvariantCulture) == ls.Text.ToLower(CultureInfo.InvariantCulture))
                        ls.Selected = true;
                }
            }
        }

        /// <summary>
        /// Uses the ModuleSettingsFilterGuid propery of the module to establish a list of potential modules for sharing their settings
        /// </summary>
        void BindComboModules(PortalModuleControl pm)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage BindComboModules BEG pm.ModuleSettingsFilterGuid:{0}.",pm.ModuleSettingsFilterGuid),PageTraceSwitch.Sw.Info);
            ModuleConfiguration m           =   GetModuleConfiguration();
            ModulesDB mdb                   =   new ModulesDB();
            Guid exguid                     =   pm.ModuleSettingsFilterGuid;
            try
            {
                ArrayList lst               =   mdb.FindModulesByGuid(portalSettings.PortalID, exguid,ModuleID);
                ModuleItem mi               =   new ModuleItem();
                mi.Title                    =   LocalizeHelper.Localize( "MODULESETTINGS_MODULE_NOMODULE","No Module");
                mi.ID                       =   0;
                lst.Insert(0, mi);
                ComboModules.DataTextField  =   "Title";
                ComboModules.DataValueField =   "ID";
                ComboModules.DataSource     =   lst;
                ComboModules.DataBind();
                ComboModules.SelectedValue  =   m.ModuleSettingsID.ToString();
            }
            catch (Exception ex)
            {
                if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleSettingsPage BindComboModules ex : {0}", ex),PageTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// The BindData helper method is used to populate a asp:datalist
        /// server control with the current "edit access" permissions
        /// set within the portal configuration system
        /// </summary>
        private void BindData()
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage BindData BEG.",PageTraceSwitch.Sw.Info);
            // Deny access if Module not in Tab. 
            ModuleConfiguration m                   =   GetModuleConfiguration();
            if ( m == null )
                PortalSecurity.AccessDenied();
            authAddRoles.Visible                    =   true;
            authDeleteRoles.Visible                 =   true;
            authEditRoles.Visible                   =   true;
            authPropertiesRoles.Visible             =   true;
            authMoveModuleRoles.Visible             =   true;
            authDeleteModuleRoles.Visible           =   true;
            authViewRoles.Visible                   =   true;
            // Update Textbox Settings
            moduleTitle.Text                        =   m.ModuleTitle;
            cacheTime.Text                          =   m.CacheTime.ToString();
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage BindData before DataBind m.PageID: {0}.", m.PageID),PageTraceSwitch.Sw.Info);
            tabDropDownList.SelectedTreeViewValue   =   m.PageID.ToString();
            tabDropDownList.DataBind();
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage BindData after DataBind tabDropDownList.Text : [{0}].", tabDropDownList.Text),PageTraceSwitch.Sw.Info);
            
            showEveryWhere.Checked                  =   m.ShowEveryWhere;

            // is the window mgmt support enabled
            allowCollapsable.Enabled                =   Config.SupportWindowMgmt;
            allowCollapsable.Checked                =   m.SupportCollapsable;
            //Get Module's model name
            PortalModuleControl pm                  =   null;
            string controlPath                      =   AddonNice.Settings.Path.WebPathCombine(AddonNice.Settings.Path.ApplicationRoot, m.DesktopSrc);
            try
            {
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage BindData LoadControl : {0}.", controlPath),PageTraceSwitch.Sw.Info);
                pm                                  =   (PortalModuleControl)LoadControl(controlPath);
            }
            catch (Exception ex)
            {
                if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleSettingsPage BindData controlPath : {0}, ex : {1}", controlPath, ex),PageTraceSwitch.Sw.Info);
                throw;
            }
            BindComboModules(pm);

            string mtp                              =   pm.GetType().BaseType.ToString();
            moduleType.Text				            =   mtp.Substring(mtp.LastIndexOf('.')+1);
            LblModuleID.Text                        =   pm.ModuleID.ToString();

            // Populate checkbox list with all security roles for this portal
            // and "check" the ones already configured for this module
            populateRoles(authEditRoles, m.AuthorizedEditRoles);
            populateRoles(authViewRoles, m.AuthorizedViewRoles);
            populateRoles(authAddRoles, m.AuthorizedAddRoles);
            populateRoles(authDeleteRoles, m.AuthorizedDeleteRoles);
            populateRoles(authMoveModuleRoles, m.AuthorizedMoveModuleRoles);
            populateRoles(authDeleteModuleRoles, m.AuthorizedDeleteModuleRoles);
            populateRoles(authPropertiesRoles, m.AuthorizedPropertiesRoles);

            if (!pm.Cacheable)
            {
                cacheTime.Text                      =   "-1";
                cacheTime.Enabled                   =   false;
            }
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage BindData END.",PageTraceSwitch.Sw.Info);
        }

        private ModuleConfiguration GetModuleConfiguration()
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage GetModuleConfiguration BEG ModuleID: {0}.", ModuleID),PageTraceSwitch.Sw.Info);
            // Obtain selected module data
            ModuleConfiguration _module             =   portalSettings.GetModuleConfiguration(ModuleID);
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleSettingsPage GetModuleConfiguration END ModuleID: {0} is null: {1}.", ModuleID, _module == null),PageTraceSwitch.Sw.Info);
            return _module;
        }

        void ModuleSettingsPage_AdminProperties(object sender, AddonNice.UI.ADNPageEventArgs e)
        {
			string url	=	HttpUrlBuilder.BuildUrl(Config.ModulesPath + "/" + Config.ModulePropertyPage, PageID, ModuleID);
            if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"ModuleSettingsPage ModuleSettingsPage_AdminProperties url: {0}",url),PageTraceSwitch.Sw.Info);
			// Redirect to module settings page
            Redirect(url,true);
		}

        #region Std Overrides

        /// <summary>
        /// Here we create the command buttons and add them to the PlaceHolders prepared
        /// </summary>
        override protected void OnPreInit(EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage OnPreInit Begin",PageTraceSwitch.Sw.Info);
            //Controls must be created here
            adminPropertiesButton       = new System.Web.UI.WebControls.ImageButton();
            adminPropertiesButton2      = new System.Web.UI.WebControls.ImageButton();
            base.OnPreInit(e);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage OnPreInit End",PageTraceSwitch.Sw.Info);
        }

        private void InitializeComponent()
        {
            Load                +=  new EventHandler(Page_Load);
            Update              +=  new PageEventHandler(ModuleSettingsPage_Update);
            AdminProperties     +=  new PageEventHandler(ModuleSettingsPage_AdminProperties);
            PlaceHolderButtons.Controls.Add(adminPropertiesButton);
            PlaceHolderButtons2.Controls.Add(adminPropertiesButton2);
            PlaceHolderButtons.Controls.Add(new LiteralControl("&#160;"));
            PlaceHolderButtons2.Controls.Add(new LiteralControl("&#160;"));
        }

        override protected void OnInit(EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage OnInit Begin",PageTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ModuleSettingsPage OnInit End",PageTraceSwitch.Sw.Info);
        }

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons2
		{
			get
			{ return PlaceHolderButtons2; }
			set { }
		}
        
        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons
		{
			get
			{ return PlaceHolderButtons; }
			set { }
		}
        #endregion

    }
}
